<template>
  <el-card>
    <div style="float:left;margin:10px 0;">
      <el-input v-model.trim="params.keyword" placeholder="ID/昵称/用户名" clearable style="width:200px;" @keyup.enter.native="search"></el-input>
      <el-button type="primary" @click="search">搜索</el-button>
      <el-button type="primary" @click="showAddModal" style="margin-left: 30px;">新增</el-button>
      <el-button type="primary" @click="exportExcel" style="margin-left: 30px;">导出数据</el-button>
    </div>

    <el-table :data="tableData" border>
      <el-table-column label="昵称" prop="nick_name" width="160"></el-table-column>
      <el-table-column label="用户名" prop="user_name" min-width="160"></el-table-column>
      <el-table-column label="角色" prop="role_name" width="160"></el-table-column>
      <el-table-column label="IP" prop="ip" width="260"></el-table-column>
      <el-table-column label="最近登录时间" prop="login_time" width="200"></el-table-column>
      <el-table-column label="注册时间" prop="reg_time" width="200"></el-table-column>
      <el-table-column label="状态" prop="status" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.status === 1">启用</span>
          <span v-if="scope.row.status === 0">停用</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" prop="op" width="300" align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="edit(scope.row.id)">编辑</el-button>
          <el-button type="warning" size="mini" @click="showRole(scope.row.user_id)">绑定角色</el-button>
          <el-button v-if="currentUserName != scope.row.user_name" type="danger" size="mini" @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination layout="prev, pager, next" :current-page="params.page" :page-size="params.rows" :page-count="6"
                   :total="total" @current-change="searchPage"></el-pagination>

    <el-dialog :visible="showMergeDialog" width="450px" @close="showMergeDialog = false">
      <div slot="title" style="text-align: left;font-size: 20px;">{{opTitle}}</div>

      <el-form ref="ruleForm" label-position="left" label-width="100px" :model="formData" :rules="rules">
        <el-form-item label="昵称：" prop="nick_name">
          <el-input v-model.trim="formData.nick_name" style="width:300px;"></el-input>
        </el-form-item>
        <el-form-item label="用户名：" prop="user_name">
          <el-input v-model.trim="formData.user_name" style="width:300px;"></el-input>
        </el-form-item>
        <el-form-item v-if="opType!==2" label="密码：" prop="password">
          <el-input v-model.trim="formData.password" type="password" style="width:300px;"></el-input>
        </el-form-item>
        <el-form-item label="是否启用：" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态" style="width:300px;">
            <el-option
              v-for="item in enableTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button @click="showMergeDialog = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog :visible="showRoleModal" width="450px" @close="showRoleModal = false">
      <div slot="title" style="text-align: left;font-size: 20px;">新增</div>

      <el-select v-model="bindParams.role_id" placeholder="请选择角色" style="width:300px;">
        <el-option
          v-for="item in roles"
          :key="item.roleId"
          :label="item.roleName"
          :value="item.roleId">
        </el-option>
      </el-select>

      <span slot="footer">
        <el-button @click="showRoleModal = false">取 消</el-button>
        <el-button type="primary" @click="bindRole">确 定</el-button>
      </span>
    </el-dialog>


  </el-card>
</template>

<script>

    import api from '../../../utils/api';

    export default {
        name: "UserManage",
        data() {

            const validatePassword = (rule, value, callback) => {
                if (this.opType === 1) {
                    var reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/;
                    console.log(reg.test(value));
                    if (!reg.test(value)) {
                        callback(new Error('请输入由字母和数字组成的密码'));
                    } else {
                        callback();
                    }
                }
            };

            return {
                currentUserName: '',
                enableTypeList: [
                    {label: '启用', value: 1},
                    {label: '停用', value: 0}
                ],
                params: {
                    rows: 10,
                    page: 1,
                    keyword: null,
                },
                total: 0,
                tableData: [],
                showMergeDialog: false,
                opType: 1,//1新增 2编辑 3详情
                opTitle: '新增',
                formData: {
                    nick_name: '',
                    user_name: '',
                    password: ''
                },
                rules: {
                    nick_name: [
                        {required: true, message: '请输入昵称', trigger: 'blur'}
                    ],
                    user_name: [
                        {required: true, message: '请输入用户昵称（登录账号）', trigger: 'blur'}
                    ],
                    password: [
                        {validator: validatePassword, trigger: 'change'}
                    ],
                },
                bindParams: {
                    user_id: null,
                    role_id: null
                },
                showRoleModal: false,
                roles: [],
            }
        },
        methods: {
            search() {
                this.params.page = 1;
                this.searchPage(1);
            },
            searchPage(page) {
                var that = this;
                that.params.page = page;
                api.ajax.get('/user/page/' + that.params.rows + '/' + that.params.page + '?keyword=' + that.params.keyword).then((result) => {
                    var data = result.data;
                    that.tableData = data.list;
                    that.total = data.total;
                }, function (result) {
                    that.$alert("获取用户列表异常", '失败!');
                })
            },
            showAddModal() {
                this.showMergeDialog = true;
                // this.$refs['ruleForm'].clearValidate();
                this.opType = 1;
                this.opTitle = '新增';
                this.formData = {
                    status: 1
                };
            },
            // resetForm(formName) {
            //     this.$refs[formName].resetFields();
            // },
            save() {
                var that = this;
                this.$refs["ruleForm"].validate((valid) => {
                    if (valid) {
                        if (this.opType === 1) {
                            api.ajax.post('user/add', that.formData)
                                .then((result) => {
                                    if (result.status == 200) {
                                        that.$message.success('新增成功');
                                        that.showMergeDialog = false;
                                        that.search();
                                    } else {
                                        that.$message(result.msg);
                                    }
                                }, (result) => {
                                    that.$alert("新增异常", '失败!');
                                })
                        } else {
                            api.ajax.post('user/update', that.formData)
                                .then((result) => {
                                    if (result.status == 200) {
                                        that.$message.success('修改成功');
                                        that.showMergeDialog = false;
                                        that.search();
                                    } else {
                                        that.$message(result.msg);
                                    }
                                }, (result) => {
                                    that.$alert("修改异常", '失败!');
                                })
                        }
                    } else {
                        return false;
                    }
                });
            },
            edit(id) {
                var that = this;
                that.opType = 2;
                that.opTitle = '编辑';
                api.ajax.get('user/detail/' + id)
                    .then((result) => {
                        if (result.status == 200) {
                            let detail = result.data;
                            that.formData = {
                                id: detail.id,
                                nick_name: detail.nick_name,
                                user_name: detail.user_name,
                                status: detail.status
                            }
                            that.showMergeDialog = true;
                        } else {
                            that.$message(result.msg);
                        }
                    })
            },
            showRole(userId) {
                this.bindParams.user_id = userId;
                this.getRoles();
                this.showRoleModal = true;
            },
            bindRole() {
                var that = this;
                if (!that.bindParams.role_id) {
                    that.$message.error('请先选择角色');
                    return;
                }
                api.ajax.post('user/bind/role', that.bindParams)
                    .then((result) => {
                        if (result.status == 200) {
                            that.$message.success('绑定成功');
                            that.showRoleModal = false;
                            that.search();
                        } else {
                            that.$message(result.msg);
                        }
                    }, (result) => {
                        that.$alert("绑定异常", '失败!');
                    })
            },
            getRoles() {
                var that = this;
                api.ajax.get("/role/get/all").then(function (result) {
                    if (result.status == 200) {
                        that.roles = result.data;
                    } else {
                        that.$message(result.msg);
                    }
                }, function (result) {
                    // console.log(result);
                    that.$alert("获取角色信息失败", '失败!');
                });
            },
            del(id) {
                var that = this;
                api.ajax.delete('user/delete/' + id)
                    .then((result) => {
                        if (result.status == 200) {
                            that.$message.success('删除成功');
                            that.search();
                        } else {
                            that.$message(result.msg);
                        }
                    })
            },
            exportExcel(){
                var that = this;
                // api.ajax.get('user/export')
                //     .then((result) => {
                //         if (result.status == 200) {
                //
                //         } else {
                //
                //         }
                //     })
            }
        },
        created() {
            this.search();
            this.currentUserName = JSON.parse(localStorage.getItem("loginUserInfo")).user_name;
        },
        mounted() {
        }
    }
</script>

<style scoped>

</style>
